//
//  HomePageViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/24.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageViewRecommendController.h"
#import "HomePageDetailViewController.h"
#import "HomePageRecommendListViewController.h"
#import "HomePageMainListViewController.h"

#import "CKSegmentBar.h"
#import "HomePageListSegmentedView.h"
#import "RPAppActivityView.h"
#import "RPAppUpdateView.h"
#import "HomePageRefreshHeader.h"

#import "AppDelegate.h"

#import "MineFollowItemModel.h"
#import "HomePageTagModel.h"
#import "HomePageItemModel.h"
#import "UpdateVersionModel.h"
#import "HomePageNavModel.h"
#import "UpdateVersionModel.h"
#import "LessonUseageModel.h"
#import "ExercisesPageModel.h"
#import "MineFollowItemModel.h"
#import "MineMessaeUnreadCountModel.h"
#import "LessonBannerModel.h"
#import "UserInfoFollowModel.h"
#import "HomePageActivityModel.h"
#import "XHPushVCTool.h"

@interface HomePageViewRecommendController ()<UIScrollViewDelegate>
/// 页面控制视图
@property (nonatomic,strong)HomePageListSegmentedView *segmentBar; /// 标签列表
/// 基本数据类型
@property (nonatomic,assign)NSInteger page; /// 分页

@property (nonatomic,assign)BOOL isHideUpdateView; /// 在线升级是否点击更新
/// list
@property (nonatomic,copy)NSArray *tags; /// 标签list
@property (nonatomic,strong)NSMutableArray *dataArray; /// 普通数据的list
@property (nonatomic,strong)NSMutableArray *systemDataArray; /// 系统消息list

@property (nonatomic,strong)UIScrollView *scrollView;

@property (nonatomic,strong)NSURLSessionTask *activityTask;
@property (nonatomic,strong)NSURLSessionTask *updateTask;

@property (nonatomic,strong)NSMutableArray *lists;


@end

@implementation HomePageViewRecommendController

- (NSMutableArray *)lists{
    if (!_lists) {
        _lists = [NSMutableArray array];
    }
    return _lists;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        
    [self setNeedsStatusBarAppearanceUpdate];
//
//    // 是否弹出在线升级和活动弹框
//    [self loadAppUpdateSource];
    
   
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}



- (HomePageListSegmentedView *)segmentBar{
    if (!_segmentBar) {
        __weak typeof(self)weakSelf = self;
        _segmentBar = [[HomePageListSegmentedView alloc]initWithCompleteBlock:^(NSInteger index) {
            if (weakSelf.lists.count == 0) {
                return;
            }
            
            HomePageRecommendListViewController *listVc = weakSelf.lists[index];
            
            if (!listVc.isRefresh) {
                listVc.isRefresh = YES;
                [listVc requestData];
            }
            [weakSelf.scrollView setContentOffset:CGPointMake(kScreenW * index, 0) animated:YES];
        }];
    }
    return _segmentBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self registNote];
    
    // 判断是否有网络
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"" completeBlock:^{
            @zf_strongify(self)
            [self setupNormalData];
        } cancelBlock:nil];
    }else{
        [self setupNormalData];
    }
    self.page = 1;
    
    self.isHideNavBar = YES;
}

- (void)setupNormalData{
    [self setUI];
    // 获取用户列表数据
    [self loadDataSource];

}

#pragma mark - 设置UI
- (void)setUI{
    
    [self.view addSubview:self.segmentBar];
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segmentBar.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}

- (void)setupScrollViewSubViews{
    if (self.lists.count == 0) {
        [self.tags enumerateObjectsUsingBlock:^(HomePageTagModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HomePageRecommendListViewController *itemVC = [[HomePageRecommendListViewController alloc]initWithTagId:obj.id];
            [self addChildViewController:itemVC];
            [self.scrollView addSubview:itemVC.view];
            
            if (idx == 0) {
                itemVC.isRefresh = YES;
                [itemVC requestData];
            }
            [self.lists addObject:itemVC];
        }];
        self.scrollView.contentSize = CGSizeMake(kScreenW * self.tags.count, 0);
        __block UIView *lastView = nil;
        [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (lastView == nil) {
                [obj mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.height.width.equalTo(self.scrollView);
                    make.leading.mas_equalTo(self.scrollView.mas_leading);
                }];
            }else{
                [obj mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.height.width.equalTo(self.scrollView);
                    make.leading.mas_equalTo(lastView.mas_trailing);
                }];
            }
            lastView = obj;
        }];
    }else{
        // 刷表
        [self updateSubViewSource];
    }
}

#pragma mark - 更新控制器数据
- (void)updateSubViewSource{
    
    [self.lists enumerateObjectsUsingBlock:^(HomePageRecommendListViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isRefresh) {
            [obj reloadData];
        }
    }];
}

#pragma mark - 处理通知
- (void)registNote{
    /// 监听用户信息中心的关注按钮 改变当前页面状态    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteHomePageItem:) name:@"deleteHomePageItem" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateHomePageList) name:@"updateUserInfoIcon" object:nil];    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLoginUserInfoFollowListStatus) name:@"updateLoginUserInfoFollowListStatus" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateItemListStatusSource:) name:@"updateItemListSource" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateFollowListStatus:) name:@"updateUserInfoFollowListStatus" object:nil];
}

//- (void)applicationBecomeActive{
//    if (self.isHideUpdateView && [[RPAppManager jsd_findVisibleViewController] isKindOfClass:[HomePageMainListViewController class]]) {
//        [self loadAppUpdateSource];
//    }
//}

- (void)updateLoginUserInfoFollowListStatus{
    [self updateUserInfoList];
}

- (void)updateUserInfoList{
    NSInteger index = self.scrollView.contentOffset.x/kScreenW;
    if (self.lists.count == 0) {
        return;
    }
    HomePageRecommendListViewController *obj = self.lists[index];
    [obj requestData];
}

- (void)updateHomePageList{
    [self.lists enumerateObjectsUsingBlock:^(HomePageRecommendListViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj reloadData];
    }];
}

- (void)updateItemListStatusSource:(NSNotification *)note{
    HomePageItemModel *itemModel = note.userInfo[@"data"];
    [self.lists enumerateObjectsUsingBlock:^(HomePageRecommendListViewController *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj reloadTargetItemWithCurrentModel:itemModel];
    }];
}

- (void)deleteHomePageItem:(NSNotification *)note{
    HomePageItemModel *itemModel = note.userInfo[@"data"];
    [self.lists enumerateObjectsUsingBlock:^(HomePageRecommendListViewController *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj reloadDataWithDeleteItem:itemModel];
    }];
}

- (void)updateFollowListStatus:(NSNotification *)note{
    MineFollowItemModel *itemModel = note.userInfo[@"data"];
    [self.lists enumerateObjectsUsingBlock:^(HomePageRecommendListViewController *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj reloadItemFollowType:itemModel.followCode userId:itemModel.userId];
    }];
}

#pragma mark - 网络请求



//- (void)loadAppUpdateSource{
//        
//    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    
//    if (appDelegate.appActivityStatus.intValue == 1) {
//        return;
//    }
//    
//    long time = [[[NSUserDefaults standardUserDefaults]objectForKey:@"updateVersionTime"] longValue];
//    // 判断是否是今天提醒
//    if ([[NSDate dateWithTimeIntervalSince1970:time]isToday]) {
//        // 展示活动框
//        [self loadActivitySource];
//    }else{
//        if (self.isHideUpdateView) {
//            self.isHideUpdateView = NO;
//        }
//        __weak typeof(self)weakSelf = self;
//        // 判断本地版本号
//        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//        [[AFHTTPSessionManager manager] POST:@"http://itunes.apple.com/cn/lookup?id=1537342377" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSString *onlineVersion = [responseObject[@"results"] firstObject][@"version"];
//            //获取更新版本信息
//            NSString *message = [responseObject[@"results"] firstObject][@"releaseNotes"];
//            NSComparisonResult reslut = [RPAppManager compareOnlineVersion:onlineVersion toVersion:app_Version];
//            // 需要更新
//            [self.updateTask cancel];
//            if (reslut == NSOrderedDescending) {
//                NSMutableDictionary *param = [NSMutableDictionary dictionary];
//                param[@"md5"] = [RPAppManager md5StrWithApi:CheckUpdate];
//                param[@"appVersion"] = app_Version;
//                param[@"deviceType"] = @1;
//                self.updateTask = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(CheckUpdate) parames:param success:^(id responseObj) {
//                    if (![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[HomePageMainListViewController class]]) {
//                        return;
//                    }
//                    if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
//                        UpdateVersionModel *versionModel = [UpdateVersionModel mj_objectWithKeyValues:responseObj[RESPONSE]];
//                        versionModel.content = message;
//                        RPAppUpdateView *updateView = [[RPAppUpdateView alloc]initWithUpdateVersionModel:versionModel completeBlock:^{
//                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/dd-up/id1537342377?mt=8"] options:@{} completionHandler:^(BOOL success) {}];
//                            weakSelf.isHideUpdateView = YES;
//                        } cancelBlock:^{
//                            [weakSelf loadActivitySource];
//                        }];
//                        [updateView showInView:self.tabBarController.view];
//                    }else{
//                        [self loadActivitySource];
//                    }
//                } failure:^(id error) {
//                    [self loadActivitySource];
//                }];
//            // 不需要更新的情况下
//            }else{
//                // 展示活动框
//                [self loadActivitySource];
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            [self loadActivitySource];
//        }];
//    }
//}
//
//- (void)loadActivitySource{
//    [self.activityTask cancel];
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    param[@"userId"] = [RPAppManager getCustomerId];
//    param[@"md5"] = [RPAppManager md5StrWithApi:GetEventGet];
//    self.activityTask = [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetEventGet) parames:param success:^(id responseObj) {
//    
//        if (![[RPAppManager jsd_findVisibleViewController] isKindOfClass:[HomePageMainListViewController class]]) {
//            return;
//        }
//        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        appDelegate.appActivityStatus = @1;
//        
//        if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
//            HomePageActivityModel *itemModel = [HomePageActivityModel mj_objectWithKeyValues:responseObj[RESPONSE]];
//            // 取出本地数据库对象
//            RLMRealm *realm = [RLMRealm defaultRealm];
//            //根据id取出本地对象
//            RLMResults *results = [[HomePageActivityModel allObjects] objectsWhere:[NSString stringWithFormat:@"id == %ld",itemModel.id]];
//            if (results.count > 0) {
//                HomePageActivityModel *lastModel = results.firstObject;
//                // 判断是否删除了banner
//                if (itemModel.delete) {
//                    [realm transactionWithBlock:^{
//                        [realm deleteObjects:results];
//                    }];
//                }else{
//                    // 每天展示一次
//                    if (lastModel.fqcy != 1) {
//                        // 判断是否是每次展示一次并且是否是今天展示过 || 判断每次都展示
//                        if ((![[NSDate dateWithTimeIntervalSince1970:lastModel.showTime] isToday] && lastModel.fqcy == 2) || lastModel.fqcy == 3) {
//                            itemModel.showTime = [NSDate date].timeIntervalSince1970;
//                            [realm transactionWithBlock:^{
//                                [realm addOrUpdateObject:itemModel];
//                            }];
//                            // 显示视图
//                            RPAppActivityView *acView = [[RPAppActivityView alloc]initWithActivityItemModel:itemModel completeBlock:^{
//            
//                                if (itemModel.type == 2) {
//                                    
//                                }else{
//                                    [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:itemModel.url paramUrl:@""];
//                                }
//                                
//                            } cancelBlock:^{
//                                
//                            }];
//                            [acView showInView:self.tabBarController.view];
//                        }
//                    }
//                }
//            }else{
//                // 判断是否删除
//                if (!itemModel.delete) {
//                    // 当前展示时间
//                    itemModel.showTime = [NSDate date].timeIntervalSince1970;
//                    // 写入数据库
//                    [realm transactionWithBlock:^{
//                        [realm addOrUpdateObject:itemModel];
//                    }];
//                    RPAppActivityView *acView = [[RPAppActivityView alloc]initWithActivityItemModel:itemModel completeBlock:^{
//                       
//                        if (itemModel.type == 2) {
//                            
//                        }else{
//                            [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:itemModel.url paramUrl:@""];
//                        }
//                    } cancelBlock:^{
//                       
//                    }];
//                    [acView showInView:self.tabBarController.view];
//                }
//            }
//        }
//    } failure:^(id error) {
//                
//        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        appDelegate.appActivityStatus = @1;
//    }];
//}




- (void)loadDataSource{
    
    [self showDataLoadState];
    
    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadUserInfo];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadTagList];
    });
        
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideDataLoadLoadState];
        // 也有可能页面进行了跳转 接口后执行了
        [self setupScrollViewSubViews];
    });
}

- (void)loadUserInfo{
    if ([RPAppManager isLogin]) {
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        // 请求用户登录信息
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = [RPAppManager getCustomerId];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUser];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUser) parames:param success:^(id responseObj) {
            UserInfoModel *userInfo = [UserInfoModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            [userInfo save];
            dispatch_semaphore_signal(sema);
        } failure:^(NSError *error) {
            dispatch_semaphore_signal(sema);
        }];
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
}

- (void)loadTagList{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTagList];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetTagList) parames:param success:^(id responseObj) {
        NSMutableArray *reslut = [HomePageTagModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        HomePageTagModel *model = [HomePageTagModel new];
        model.topicName = @"全部";
        [reslut insertObject:model atIndex:0];
        self.tags = reslut;
        NSMutableArray *titleArray = [NSMutableArray array];
        [self.tags enumerateObjectsUsingBlock:^(HomePageTagModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [titleArray addObject:obj.topicName];
        }];
        self.segmentBar.itemArray = self.tags;
        
        dispatch_semaphore_signal(sema);
        
    } failure:^(NSError *error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
}

#pragma mark - method
- (void)addMethod{
    [MobClick event:@"homePage_add_click"];
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
 
    [MGJRouter openURL:@"local://ddup/release" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/kScreenW;
    self.segmentBar.currentIndex = index;
    
    HomePageRecommendListViewController *listVc = self.lists[index];
    
    if (!listVc.isRefresh) {
        listVc.isRefresh = YES;
        [listVc requestData];
    }
}


-(void)dealloc{
    NSLog(@"%s",__func__);
}
@end
